import React, {
  useState,
  useRef,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Select,
  DatePicker,
  Table,
  Popconfirm,
  Tag,
  message,
} from 'antd';
import type { FormInstance } from 'antd';
import { MonitorOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import STable from '@/pages/component/table/index.tsx'; // 假设已转换STable组件
import Model from './model.tsx'; // 假设已转换Model组件
import { columns, search, formConfig, rules } from './form.tsx'; // 需要转换form.js

const { RangePicker } = DatePicker;

interface SearchItem {
  field: string;
  label: string;
  component: string;
  span?: number;
  componentProps?: any;
}

const SysModule = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [formState, setFormState] = useState({ pageNum: 1, pageSize: 10 });
  const tableRef = useRef<any>();
  const modelRef = useRef<any>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 初始化字典
  useEffect(() => {}, []);

  // 加载表格数据
  const loadData = async (params: any) => {
    const mergedParams = { ...formState, ...params };
    try {
      return new Promise((resolve) => {
        resolve({
          total: 2,
          rows: [
            {
              id: '1821730112123826178',
              name: '班组测试1',
              ondutyUserVoList: null,
            },
            {
              id: '1801901892308897793',
              name: 'CT班组',
              ondutyUserVoList: null,
            },
          ],
          code: 200,
          msg: '查询成功',
        });
      });
    } catch (error) {
      message.error('数据加载失败');
      return { data: [], total: 0 };
    }
  };

  // 处理查询
  const handleSearch = () => {
    tableRef.current?.refresh();
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setFormState({ pageNum: 1, pageSize: 10 });
    tableRef.current?.refresh(true);
  };

  // 处理操作
  const handleDetail = async (action: string, record?: any) => {
    const disabled = action === '详情';

    if (action === '新增') {
      modelRef.current?.handleVisible(true, action, {});
      return;
    }

    try {
      const res = { data: [] };
      modelRef.current?.handleVisible(true, action, res.data, disabled);
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 处理删除
  const handleDelete = async (record: any) => {
    try {
      message.success('删除成功');
      tableRef.current?.refresh();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 表格列配置
  const tableColumns = (columns || []).map((col) => {
    if (col.dataIndex === 'action') {
      return {
        ...col,
        render: (_: any, record: any) => (
          <span>
            <a onClick={() => handleDetail('详情', record)}>详情</a>
            <a
              onClick={() => handleDetail('编辑', record)}
              style={{ marginLeft: 8 }}
            >
              编辑
            </a>
            <Popconfirm
              title="确定要删除该条数据吗？"
              onConfirm={() => handleDelete(record)}
            >
              <a style={{ color: 'red', marginLeft: 8 }}>删除</a>
            </Popconfirm>
          </span>
        ),
      };
    }
    if (col.dataIndex === 'icon') {
      return {
        ...col,
        render: (icon: any, record: any) => (
          <Tag color={record.color}>
            {icon === 'MonitorOutlined' ? <MonitorOutlined /> : null}
          </Tag>
        ),
      };
    }
    return col;
  });

  return (
    <div>
      {/* <Card
        bordered={false}
        bodyStyle={{ paddingBottom: 0 }}
        style={{ borderRadius: 8, marginBottom: 10 }}
      >
        <Form
          form={search}
          layout="vertical"
          className="ant-advanced-search-form"
        >
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(24, 1fr)',
              gap: 24,
            }}
          >
            {(search || []).map((item: SearchItem) => (
              <div
                key={item.field}
                style={{ gridColumn: `span ${item.span || 6}` }}
              >
                <Form.Item name={item.field} label={item.label}>
                  {item.component === 'Input' && (
                    <Input {...item.componentProps} />
                  )}
                  {item.component === 'Rangepicker' && (
                    <RangePicker {...item.componentProps} />
                  )}
                  {item.component === 'ApiSelect' && (
                    <Select
                      {...item.componentProps}
                      fieldNames={{ label: 'dictValue', value: 'dictValue' }}
                    />
                  )}
                </Form.Item>
              </div>
            ))}
            <div style={{ gridColumn: 'span 6', textAlign: 'right' }}>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
              <Button style={{ margin: '0 8px' }} onClick={handleReset}>
                重置
              </Button>
            </div>
          </div>
        </Form>
      </Card> */}

      <Card bordered={false} style={{ borderRadius: 8, marginBottom: 10 }}>
        <STable
          ref={tableRef}
          columns={tableColumns}
          data={loadData}
          toolConfig={{ refresh: true, height: true, columnSetting: true }}
          operator={
            <Button type="primary" onClick={() => handleDetail('新增')}>
              新增班组
            </Button>
          }
        />
      </Card>

      <Model
        ref={modelRef}
        form={formConfig}
        rules={rules}
        refresh={() => {
          handleReset();
          tableRef.current?.refresh(true);
        }}
      />
    </div>
  );
};

export default SysModule;
